﻿using BuyWithoutLoseMoney.Core.Models;
using BuyWithoutLoseMoney.Core.Repositories;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using System.Web;

namespace BuyWithoutLose.Areas.Admin.Controllers
{
    /// <summary>
    /// 后台登录
    /// </summary>
    [Area("Admin")]
    [AllowAnonymous]
    public class LoginController : Controller
    {
        private readonly IRepository<LoginUser, int> _loginUserRepository;
        public LoginController(IRepository<LoginUser, int> loginUserRepository)
        {
            _loginUserRepository = loginUserRepository;
        }
        /// <summary>
        /// 后台登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 后台登录验证
        /// </summary>
        /// <param name="LoginName">用户名</param>
        /// <param name="LoginPwd">密码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(string LoginName, string LoginPwd)
        {
            //根据用户名去验证用户是否存在
            var Manager = await _loginUserRepository.FirstOrDefaultAsync(x => x.LoginName == LoginName);
            bool isSuccess = false;
            string msg = "用户名或密码不正确";
            //用户名存在，验证密码是否正确
            if (Manager != null && Manager.LoginPwd == LoginPwd)
            {
                CookieOptions options = new CookieOptions();
                // 设置过期时间
                options.Expires = DateTime.Now.AddHours(2);
                HttpContext.Response.Cookies.Append("setCookieExpires",LoginName, options);

                isSuccess = true;
                msg = "登录成功!";
            }
            return Json(new { isSuccess, msg });
        }
    }
}
